package com.ebt.m.proposal_v2.widget.dialog;

import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.view.View;

import com.ebt.m.R;
import com.ebt.m.proposal_v2.base.Constant;
import com.ebt.m.proposal_v2.bean.AudioTap;
import com.ebt.m.proposal_v2.bean.event.EventTapWindowClose;
import com.ebt.m.proposal_v2.utils.ViewUtils;
import com.ebt.m.proposal_v2.voice.view.AudioView;
import com.ebt.m.proposal_v2.voice.view.RecordingView;
import com.ebt.m.commons.utils.Logger;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.File;

/**
 * 语音录制窗口
 *
 * @author archer.qi
 *         Created on 2017/5/18.
 */
public class ProposalTapDialog extends EBTBottomWrapDialogBase {

    private View mBodyView;
    private RecordingView mRecordingView;
    private AudioView mAudioView;

    private FragmentManager fragmentManager;
    private AudioTap mCurrentTap;
    private OnProposalTapListener mListener;

    @Override
    public void init() {
        initTopAndBottomBar();
        initBodyView();
        initResource();
        EventBus.getDefault().register(this);
    }

    @Override
    public void dismiss() {
        EventBus.getDefault().unregister(this);
        super.dismiss();
    }

    @Subscribe
    public void onEvent(EventTapWindowClose ev) {
        dismiss();
    }

    private void initTopAndBottomBar() {
        setTitle("添加语音讲解");
        setNegativeButton("取消", v -> dismiss());
        setPositiveButton("完成", v -> onTapComplete());
    }

    private void initBodyView() {
        mBodyView = ViewUtils.inflate(getActivity(), R.layout.dialog_proposal_tap);
        addDialogBody(mBodyView);
        mRecordingView = (RecordingView) mBodyView.findViewById(R.id.dialogTap_record);
        mAudioView = (AudioView) mBodyView.findViewById(R.id.dialogTap_audio);
        if (fragmentManager != null) {
            mRecordingView.setFragmentManager(fragmentManager);
            mAudioView.setFragmentManager(fragmentManager);
        }
        mRecordingView.setOnRecordCompleteListener((fileName, duration) -> {
            /**
             * 录音完成
             * 保存为本地录音
             */
            if (TextUtils.isEmpty(fileName)) {
                // 无效录音
            } else {
                if (!new File(fileName).exists()) {
                    return;
                }
                showAudioResource();
                mCurrentTap = createLocalAudioTap(duration);
                mAudioView.setAudio(mCurrentTap);
            }
        });
        mAudioView.setOnDeleteListener(tap -> {
            /**
             * 语音删除
             * 服务端原有语音： 删除接口 - > 删除本地文件 -> 对象置空
             * 本地添加语音： 删除本地文件 -> 对象置空
             */
            if (tap == null) {
                return;
            }
            if (tap.fromServer) { // 如果是服务端的录音，调用接口删除
                if (tap != null && !TextUtils.isEmpty(tap.id)) {
                    if (mListener != null) {
                        mListener.onTapDelete(tap);
                    }
                }
            }
            new File(tap.path).deleteOnExit(); /* 删除本地文件*/
            mCurrentTap = null;
            showRecording();
        });
    }

    private void initResource() {
        if (mCurrentTap == null) {
            // 该计划书未关联语音，显示录制
            showRecording();
        } else {
            // 该计划书关联语音，显示资源
            showAudioResource();
            mAudioView.setAudio(mCurrentTap);
        }
    }

    /**
     * 显示录音
     */
    private void showRecording() {
        mRecordingView.setVisibility(View.VISIBLE);
        mAudioView.setVisibility(View.GONE);
    }

    /**
     * 显示资源
     */
    private void showAudioResource() {
        mRecordingView.setVisibility(View.GONE);
        mAudioView.setVisibility(View.VISIBLE);
    }

    /**
     * 录音完毕后，生成一个本地录音对象
     *
     * @return
     */
    private AudioTap createLocalAudioTap(long duration) {
        AudioTap audioTap = new AudioTap();
        audioTap.fromServer = false;
        audioTap.path = Constant.outputTap;
        Logger.i("->ProposalTapDialog的时长： " + duration);
        if (duration > 120) {
            audioTap.duration = 120;
        } else {
            audioTap.duration = duration;
        }
        return audioTap;
    }

    /**
     * 点击完成
     * 如果有录音，且来自本地，则上传
     */
    private void onTapComplete() {
        if (mCurrentTap != null && !mCurrentTap.fromServer) {
            if (mListener != null) {
                mListener.onTapUpload(mCurrentTap);
            }
        }
        dismiss();
    }

    /*必须添加*/
    public ProposalTapDialog supportFragmentManager(FragmentManager fragmentManager) {
        this.fragmentManager = fragmentManager;
        return this;
    }

    /**
     * 设置从网络请求得到的Tap
     *
     * @param tap
     * @return
     */
    public ProposalTapDialog setData(AudioTap tap) {
        if (tap != null) {
            tap.fromServer = true;
        }
        mCurrentTap = tap;
        return this;
    }

    public ProposalTapDialog setOnTapListener(OnProposalTapListener listener) {
        mListener = listener;
        return this;
    }

    public interface OnProposalTapListener {
        /**
         * 网络删除
         *
         * @param tap
         */
        void onTapDelete(AudioTap tap);

        /**
         * 网络上传
         *
         * @param tap
         */
        void onTapUpload(AudioTap tap);
    }
}
